import { Node } from '../core/node.js';

export class AnimatorController extends Node {
    constructor() {
        super();

        this._params = {};
        this._animationClips = [];
        this._currentAnimationClip = null;
        this._transitions = [];
    }

    //添加片段
    addClip(animationClip) {
        this._animationClips.push(animationClip);

        if (this._currentAnimationClip == null) {
            this._currentAnimationClip = animationClip;
        }

        this.add(animationClip);
    }

    //添加过渡条件
    addTransition(transition) {
        this._transitions.push(transition);
    }

    //设置默认播放片段
    set current(animationClip) {
        this._currentAnimationClip = animationClip;
    }

    get current() {
        return this._currentAnimationClip;
    }

    //更新
    onUpdate(timestamp, frameDelta) {
        if (!this._currentAnimationClip) return;

        let toCache = [];

        for (let transition of this._transitions) {
            if (transition.from == this._currentAnimationClip) {
                let hasCache = false;

                //循环所有可能过渡的条件
                for (let to of toCache) {
                    if (to.to == transition.to) {//前面的条件都通过了，才判断当前过渡条件
                        to.isOk = to.isOk && transition.isOk(this._params[transition.paramName]);
                        hasCache = true;
                    }
                }

                if (!hasCache) {
                    toCache.push({
                        to: transition.to,
                        isOk: transition.isOk(this._params[transition.paramName])
                    });
                }
            }
        }

        for (let to of toCache) {
            if (to.isOk) {
                this._currentAnimationClip.stop();
                this._currentAnimationClip = to.to;
                this._currentAnimationClip.reset();
            }
        }

        this._currentAnimationClip.play(frameDelta);

        for (let item in this._params) {
            delete this._params[item]
        }
    }

    //设置参数
    setParams(name, value) {
        this._params[name] = value;
    }
}